<?php
namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\ValidateException;
use App\Exception\HttpException;
use Hyperf\Database\Exception\QueryException;
use Hyperf\Contract\StdoutLoggerInterface;
use Throwable;


class MyExceptionHandler extends  ExceptionHandler
{
	
	private $error_log_db = true;	//异常日志是否写入数据库
	
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

	
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
		$status = $throwable->getCode();
		
        if ($throwable instanceof ValidateException) {
            $data = json_encode([
                'status' => $status ? $status : 411,
                'msg' => $throwable->getMessage()
            ], JSON_UNESCAPED_UNICODE);

            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
		
		if ($throwable instanceof QueryException) {
			if($this->error_log_db){
				$event['msg'] = $throwable->getMessage();
				event(new \App\Event\ExceptionLogEvent($event));
			}
			
            $data = json_encode([
                'status' => $status ? $status : 500,
                'msg' => config('app.debug') ? $throwable->getMessage() : '系统错误'
            ], JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
		
		if ($throwable instanceof HttpException) {
			if($this->error_log_db){
				$event['msg'] = $throwable->getMessage();
				event(new \App\Event\ExceptionLogEvent($event));
			}
			
            $data = json_encode([
                'status' => $status ? $status : 412,
                'msg' => config('app.debug') ? $throwable->getMessage() : '系统错误'
            ], JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
		
		$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
		
        return $response;
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
